import { Component, PropsWithChildren } from 'react';
import Taro from '@tarojs/taro';

import dayjs from 'dayjs';
import zhcn from 'dayjs/locale/zh-cn';
import './app.scss';
import { initAppLog, log } from '@/utils/appLog';
import ErrorComp from '@/components/ErrorComp';

dayjs.locale('zh-cn', zhcn);

class App extends Component<PropsWithChildren> {
  state = {
    isErr: false,
  };
  componentDidMount() {
    log('App componentDidMount');
  }
  componentDidCatch(error) {
    console.log('App componentDidCatch ' + JSON.stringify(error));
    log('App componentDidCatch ' + JSON.stringify(error));
    Taro.showModal({
      title: 'app异常闪退',
      content: JSON.stringify(error),
      showCancel: false,
    });
    this.setState({
      isErr: true,
    });
  }
  async onLaunch(options) {
    console.log('launch', options);
    await initAppLog();
    log('App onLaunch ' + JSON.stringify(options));
  }

  componentDidShow(options) {
    log('App componentDidShow ' + JSON.stringify(options));
  }

  componentDidHide() {}

  onError(error) {
    console.log('App onError ' + JSON.stringify(error));
    log('App onError ' + JSON.stringify(error));
  }

  // this.props.children 是将要会渲染的页面
  render() {
    if (this.state.isErr) {
      return <ErrorComp />;
    }
    return this.props.children;
  }
}
export default App;

if (process.env.TARO_ENV === 'rn') {
  /* eslint-disable */
  // @ts-ignore
  global.XMLHttpRequest = global.originalXMLHttpRequest ? global.originalXMLHttpRequest : global.XMLHttpRequest;
  // @ts-ignore
  global.FormData = global.originalFormData ? global.originalFormData : global.FormData;
  // @ts-ignore
  fetch; // Ensure to get the lazy property
  // @ts-ignore
  if (window.__FETCH_SUPPORT__) {
    // it's RNDebugger only to have
    // @ts-ignore
    window.__FETCH_SUPPORT__.blob = false;
  } else {
    /*
     * Set __FETCH_SUPPORT__ to false is just work for `fetch`.
     * If you're using another way you can just use the native Blob and remove the `else` statement
     */
    global.Blob = global.originalBlob ? global.originalBlob : global.Blob;
    global.FileReader = global.originalFileReader ? global.originalFileReader : global.FileReader;
  }
  /* eslint-enable */

  const rn = require('react-native');
  rn.LogBox.ignoreLogs([
    '`new NativeEventEmitter()` was called with a non-null argument without the required',
    'Cannot update during an existing state transition',
  ]);
}
if (process.env.TARO_ENV === 'h5') {
  // @ts-ignore
  window['dayjs'] = dayjs;
}
